using System;
using System.Web;
using System.Net.Mail;

/// <summary>
/// Summary description for MailManager
/// </summary>
/// 
namespace CE.Mail
{
    public class MyMailManager
    {
        #region Private Variable
        private MailMessage mail = null;
        private MailAddress mailAddress = null;
        private SmtpClient mailClient = null;
        private int clientPort = -1;
        private string clientHost = String.Empty;
        private bool isEnabledSsl = false;
        private int mailType = -1;
        private string mailBody = "";
        private MailPriority mailPriority = MailPriority.Normal;

        static string smtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPHostName");
        static string smtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPPort");
        static string smtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPAccount");
        static string smtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPDisplayName");
        static string smtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPReplyTo");
        static string smtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPAuthCode");
        static bool smtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("SMTPSslEnable"));
        static string _IsLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsLive");
        static string _addToSubjectTitle = "[TS] ";
        #endregion

        public MyMailManager()
        {
            mailClient = new SmtpClient();
            mailClient.Host = "smtp.jaring.my";
            mailClient.Port = 587;
            mailClient.EnableSsl = false;
        }

        public MyMailManager(string HostName, string Port, bool EnableSSL, string Account, string AuthCode)
        {
            smtphost = HostName;
            smtpenablessl = EnableSSL;
            smtpport = Port;
            smtpaccount = Account;
            smtpauthcode = AuthCode;
        }

        public static bool SendPasswordResetLink(string UserName, string EmailAddress, string AuthSalt, string UniquiId, CE.Global.CEUserType UserType)
        {
            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "";
            string ConfirmPath = "";
            string userType = "";
            //domainUrl = "http://" + myUri.Host;
            domainUrl = "http://" + myUri.Host + ":" + myUri.Port;
            userType = "Customer";
            ConfirmPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ResetCustomerPasswordPath");

            string confirmUrl = domainUrl;
            string imgUrl = domainUrl;
            confirmUrl += ConfirmPath;

            imgUrl += CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

            string mailBody = "";
            //mailBody += "<img src='" + imgUrl + "' />";
            mailBody += "<br>Your Account is : <b>" + UserName + "</b><br>";
            mailBody += "<br><a href='" + confirmUrl + "?authkey=" + AuthSalt + "&uid=" + UniquiId + "'>Click Here</a> to reset your User Account's Password.";
            mailBody += "<br><br><br>Thank you very much!";
            mailBody += "<br>Regards,";
            mailBody += "<br>Teledirect Membership Service";

            string noreplysmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPHostName");
            string noreplysmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPPort");
            string noreplysmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPAccount");
            string noreplysmtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPDisplayName");
            string noreplysmtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPReplyTo");
            string noreplysmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPAuthCode");
            bool noreplysmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPSslEnable"));

            bool _result = SendMailNew(noreplysmtphost,
                        Convert.ToInt32(noreplysmtpport),
                        noreplysmtpaccount,
                        noreplysmtpauthcode,
                        noreplysmtpdisplayname,
                        noreplysmtpaccount,
                        userType,
                        EmailAddress,
                        "",
                        "",
                        noreplysmtpreplyto,
                        "Password Recovery - Teledirect.com.sg",
                        mailBody,
                        noreplysmtpenablessl);
            return _result;
        }

        public static bool SendECertificate(string UserName, string EmailAddress, string CourseTitle, string UniquiId, CE.Global.CEUserType UserType)
        {
            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "";
            string ConfirmPath = "";
            string userType = "";
            //domainUrl = "http://" + myUri.Host;
            domainUrl = "http://" + myUri.Host + ":" + myUri.Port;
            userType = "Customer";
            ConfirmPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ECertificatePath");

            string confirmUrl = domainUrl;
            string imgUrl = domainUrl;
            confirmUrl += ConfirmPath;

            imgUrl += CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

            string mailBody = "";
            //mailBody += "<img src='" + imgUrl + "' />";
            mailBody += "<br>Congratulation <b>" + UserName + ",</b><br>";
            mailBody += "<br>You have passed the course <b>" + CourseTitle + "</b><br>";
            mailBody += "<br>You can download your e-certificate <a href='" + confirmUrl + "'>Here</a>.";
            mailBody += "<br><br><br>Thank you very much!";
            mailBody += "<br>Regards,";
            mailBody += "<br>Trainingdirect";

            string noreplysmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPHostName");
            string noreplysmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPPort");
            string noreplysmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPAccount");
            string noreplysmtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPDisplayName");
            string noreplysmtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPReplyTo");
            string noreplysmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPAuthCode");
            bool noreplysmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPSslEnable"));

            bool _result = SendMailNew(noreplysmtphost,
                        Convert.ToInt32(noreplysmtpport),
                        noreplysmtpaccount,
                        noreplysmtpauthcode,
                        noreplysmtpdisplayname,
                        noreplysmtpaccount,
                        userType,
                        EmailAddress,
                        "",
                        "",
                        noreplysmtpreplyto,
                        "Certificate - Trainingdirect.org",
                        mailBody,
                        noreplysmtpenablessl);
            return _result;
        }

        public static bool SendMailNew(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sReplyToEmail, string sHeader, string sMessage, bool fSSL)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            //System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();

            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
            //if (fSSL)
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

            //if (sUserName.Length == 0)
            //{
            //    //Ingen auth 
            //}
            //else
            //{
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
            //}

            //Mail.To = sToEmail;
            //Mail.Cc = sCCEmail;
            //Mail.Bcc = sBCCEmail;
            //Mail.From = sFromEmail;
            //Mail.Subject = sHeader;
            //Mail.Body = sMessage;            
            //Mail.BodyFormat = System.Web.Mail.MailFormat.Html;

            try
            {
                if (_IsLive == "1")
                {
                    _addToSubjectTitle = "";
                }
                else
                {
                    _addToSubjectTitle = "[TS] ";
                }
                sHeader = _addToSubjectTitle + sHeader;

                MailMessage Mail = new MailMessage();

                if (sToEmail != "")
                {
                    string[] sGetToEmails = sToEmail.Split(';');

                    foreach (string toemail in sGetToEmails)
                    {
                        if (toemail != "")
                            Mail.To.Add(new MailAddress(toemail));
                    }
                }

                if (sCCEmail != "")
                {
                    string[] sGetCCEmails = sCCEmail.Split(';');

                    foreach (string ccemail in sGetCCEmails)
                    {
                        if (ccemail != "")
                            Mail.CC.Add(new MailAddress(ccemail));
                    }
                }

                if (sBCCEmail != "")
                {
                    string[] sGetBCCEmails = sBCCEmail.Split(';');

                    foreach (string bccemail in sGetBCCEmails)
                    {
                        if (bccemail != "")
                            Mail.Bcc.Add(new MailAddress(bccemail));
                    }

                }

                Mail.From = new MailAddress(sFromEmail, sFromName); ;
                Mail.Subject = sHeader;
                Mail.Body = sMessage;
                Mail.IsBodyHtml = true;
                Mail.ReplyTo = new MailAddress(sReplyToEmail);

                //System.Web.Mail.SmtpMail.SmtpServer = sHost;
                //System.Web.Mail.SmtpMail.Send(Mail);                

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }

                object userState = Mail;

                smtp.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                smtp.SendAsync(Mail, userState);

            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMailNew Exception");

                //string cxerrorsmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPAccount");
                //if (sUserName != cxerrorsmtpaccount)
                //{
                //    string _errorMessage = "<table>";
                //    _errorMessage += "<tr><td>Exception</td><td>:</td><td>" + Ex.ToString() + "</td></tr>";
                //    _errorMessage += "<tr><td>Function</td><td>:</td><td>" + "SendMailNew of MyMailManager" + "</td></tr>";
                //    _errorMessage += "<tr><td>Host</td><td>:</td><td>" + sHost + "</td></tr>";
                //    _errorMessage += "<tr><td>Port</td><td>:</td><td>" + nPort.ToString() + "</td></tr>";
                //    _errorMessage += "<tr><td>User Name</td><td>:</td><td>" + sUserName + "</td></tr>";
                //    _errorMessage += "<tr><td>Password</td><td>:</td><td>" + sPassword + "</td></tr>";
                //    _errorMessage += "<tr><td>From Email</td><td>:</td><td>" + sFromEmail + "</td></tr>";
                //    _errorMessage += "<tr><td>To Email</td><td>:</td><td>" + sToEmail + "</td></tr>";
                //    _errorMessage += "<tr><td>Subject</td><td>:</td><td>" + sHeader + "</td></tr>";
                //    _errorMessage += "<tr><td>Mail Message</td><td>:</td><td>" + sMessage + "</td></tr>";
                //    SendErrorMessage("Mail Sending", _errorMessage);
                //}
                return false;
            }
            return true;
        }

        public static bool SendMailNewByAttachments(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sCCEmail, string sBCCEmail, string sReplyToEmail, string sHeader, string sMessage, bool fSSL, string[] fileList)
        {
            if (sToName.Length == 0)
                sToName = sToEmail;
            if (sFromName.Length == 0)
                sFromName = sFromEmail;

            //System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();

            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

            //Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
            //if (fSSL)
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

            //if (sUserName.Length == 0)
            //{
            //    //Ingen auth 
            //}
            //else
            //{
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
            //    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
            //}

            //Mail.To = sToEmail;
            //Mail.Cc = sCCEmail;
            //Mail.Bcc = sBCCEmail;
            //Mail.From = sFromEmail;
            //Mail.Subject = sHeader;
            //Mail.Body = sMessage;            
            //Mail.BodyFormat = System.Web.Mail.MailFormat.Html;

            try
            {
                if (_IsLive == "1")
                {
                    _addToSubjectTitle = "";
                }
                else
                {
                    _addToSubjectTitle = "[TS] ";
                }
                sHeader = _addToSubjectTitle + sHeader;

                MailMessage Mail = new MailMessage();

                if (sToEmail != "")
                {
                    string[] sGetToEmails = sToEmail.Split(';');

                    foreach (string toemail in sGetToEmails)
                    {
                        if (toemail != "")
                            Mail.To.Add(new MailAddress(toemail));
                    }
                }

                if (sCCEmail != "")
                {
                    string[] sGetCCEmails = sCCEmail.Split(';');

                    foreach (string ccemail in sGetCCEmails)
                    {
                        if (ccemail != "")
                            Mail.CC.Add(new MailAddress(ccemail));
                    }
                }

                if (sBCCEmail != "")
                {
                    string[] sGetBCCEmails = sBCCEmail.Split(';');

                    foreach (string bccemail in sGetBCCEmails)
                    {
                        if (bccemail != "")
                            Mail.Bcc.Add(new MailAddress(bccemail));
                    }

                }

                Mail.From = new MailAddress(sFromEmail, sFromName); ;
                Mail.Subject = sHeader;
                Mail.Body = sMessage;
                Mail.IsBodyHtml = true;
                Mail.ReplyTo = new MailAddress(sReplyToEmail);

                for (int i = 0; i < fileList.Length; i++)
                {
                    System.Net.Mail.Attachment attachment;
                    attachment = new System.Net.Mail.Attachment(fileList[i].ToString());
                    Mail.Attachments.Add(attachment);
                }

                //System.Web.Mail.SmtpMail.SmtpServer = sHost;
                //System.Web.Mail.SmtpMail.Send(Mail);                

                SmtpClient smtp = new SmtpClient();
                smtp.Port = nPort;
                smtp.Host = sHost;
                smtp.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);

                if (fSSL)
                {
                    smtp.EnableSsl = true;
                }



                object userState = Mail;

                smtp.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                smtp.SendAsync(Mail, userState);

            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMailNew Exception");

                //string cxerrorsmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPAccount");
                //if (sUserName != cxerrorsmtpaccount)
                //{
                //    string _errorMessage = "<table>";
                //    _errorMessage += "<tr><td>Exception</td><td>:</td><td>" + Ex.ToString() + "</td></tr>";
                //    _errorMessage += "<tr><td>Function</td><td>:</td><td>" + "SendMailNew of MyMailManager" + "</td></tr>";
                //    _errorMessage += "<tr><td>Host</td><td>:</td><td>" + sHost + "</td></tr>";
                //    _errorMessage += "<tr><td>Port</td><td>:</td><td>" + nPort.ToString() + "</td></tr>";
                //    _errorMessage += "<tr><td>User Name</td><td>:</td><td>" + sUserName + "</td></tr>";
                //    _errorMessage += "<tr><td>Password</td><td>:</td><td>" + sPassword + "</td></tr>";
                //    _errorMessage += "<tr><td>From Email</td><td>:</td><td>" + sFromEmail + "</td></tr>";
                //    _errorMessage += "<tr><td>To Email</td><td>:</td><td>" + sToEmail + "</td></tr>";
                //    _errorMessage += "<tr><td>Subject</td><td>:</td><td>" + sHeader + "</td></tr>";
                //    _errorMessage += "<tr><td>Mail Message</td><td>:</td><td>" + sMessage + "</td></tr>";
                //    SendErrorMessage("Mail Sending", _errorMessage);
                //}
                return false;
            }
            return true;
        }

        static void MailDeliveryComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            //Console.WriteLine("Message \"{0}\".", e.UserState);

            if (e.Error != null)
            {
                try
                {
                    //Get the Original MailMessage object
                    MailMessage mail = (MailMessage)e.UserState;

                    //write out the subject
                    string subject = mail.Subject;

                    System.Text.StringBuilder errorMsg = new System.Text.StringBuilder();
                    errorMsg.Append(string.Format("An error occurred sending message [{0}]. {1}", e.UserState.ToString(), e.Error.Message));

                    if (e.Error.InnerException != null)
                        errorMsg.Append(Environment.NewLine + "Inner exception message: " + e.Error.InnerException.Message);

                    errorMsg.Append(Environment.NewLine + "Subject: " + subject);
                    errorMsg.Append(Environment.NewLine + "Sender: " + mail.Sender.Address.ToString());
                    errorMsg.Append(Environment.NewLine + "Sender Host: " + mail.Sender.Host.ToString());
                    errorMsg.Append(Environment.NewLine + "From : " + mail.From.Address.ToString());
                    errorMsg.Append(Environment.NewLine + "From Host : " + mail.From.Host.ToString());
                    string _toAddresses = "";
                    foreach (MailAddress _msgMail in mail.To)
                    {
                        _toAddresses += _msgMail.Address.ToString() + ";";
                    }
                    errorMsg.Append(Environment.NewLine + "To : " + _toAddresses);
                    CreateMailDeliveryExceptionLog("SendMailNew MailDeliveryComplete Exception", errorMsg);
                }
                catch (Exception Ex)
                {
                    Ex = null;
                }
            }
            else if (e.Cancelled)
            {
                //Console.WriteLine("Sending of email cancelled.");
            }
            else
            {
                //Console.WriteLine("Message sent.");
            }
        }

        public static bool SendWebMailNewByAttachments(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
        string sToName, string sToEmail, string sToCCEmail, string sToBCCEmail, string sReplyToEmail, string sHeader, string sMessage, bool fSSL, string[] fileList)
        {
            bool _retValue = false;
            try
            {
                if (_IsLive == "1")
                {
                    _addToSubjectTitle = "";
                }
                else
                {
                    _addToSubjectTitle = "[TS] ";
                }
                sHeader = _addToSubjectTitle + sHeader;

                if (sToName.Length == 0)
                    sToName = sToEmail;
                if (sFromName.Length == 0)
                    sFromName = sFromEmail;

                System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;

                Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
                if (fSSL)
                    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpusessl"] = "true";

                if (sUserName.Length == 0)
                {
                    //Ingen auth 
                }
                else
                {
                    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
                    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
                    Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
                }


                Mail.To = sToEmail;
                Mail.From = sFromName + "<" + sFromEmail + ">";
                Mail.Subject = sHeader;
                Mail.Body = sMessage;
                Mail.Cc = sToCCEmail;
                Mail.Bcc = sToBCCEmail;
                Mail.Headers.Add("Reply-To", sReplyToEmail);

                for (int i = 0; i < fileList.Length; i++)
                {
                    Mail.Attachments.Add(new System.Web.Mail.MailAttachment(fileList[i].ToString()));
                }

                Mail.BodyFormat = System.Web.Mail.MailFormat.Html;

                System.Web.Mail.SmtpMail.SmtpServer = sHost;
                System.Web.Mail.SmtpMail.Send(Mail);
                _retValue = true;
            }
            catch (Exception Ex)
            {
                string _emailSetting = "Host : " + sHost + " From Email : " + sUserName + " To Email : " + sToEmail + " Subject : " + sHeader;
                CreateExceptionLog(Ex, _emailSetting, "SendMailNew By Attachments Exception");
                _retValue = false;
            }

            return _retValue;
        }

        public static bool SendErrorMessage(string TitlePrefix, string EmailMessage)
        {
            string _errormessagereceiver = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ErrorMessageReceiver");

            string cxerrorsmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPHostName");
            string cxerrorsmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPPort");
            string cxerrorsmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPAccount");
            string cxerrorsmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPAuthCode");
            bool cxerrorsmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXErrorSMTPSslEnable"));

            bool _result = SendMailNew(cxerrorsmtphost,
                        Convert.ToInt32(cxerrorsmtpport),
                        cxerrorsmtpaccount,
                        cxerrorsmtpauthcode,
                        "Trainingdirect",
                        cxerrorsmtpaccount,
                        TitlePrefix + " TD Error Message Service",
                        _errormessagereceiver,
                        "",
                        "",
                        cxerrorsmtpaccount,
                        TitlePrefix + " Error - " + DateTime.Now.ToString(),
                        EmailMessage,
                        cxerrorsmtpenablessl);

            return _result;
        }

        private static void CreateExceptionLog(Exception Ex, string EmailSettingInfo, string strLocation)
        {
            String[] _fileContent = new String[7];
            _fileContent[0] = "Email Setting : " + EmailSettingInfo;
            _fileContent[1] = "Source : " + Ex.Source;
            _fileContent[2] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[3] = "Stack Trace :" + Ex.StackTrace.ToString();
            _fileContent[4] = "Target Site : " + Ex.TargetSite.ToString();
            _fileContent[5] = "Location : " + "MyMailManager - " + strLocation;
            _fileContent[6] = "Message : " + Ex.Message;

            WriteExceptionLog("Mail_", _fileContent);
        }

        private static void WriteExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                CE.InputOut.MyIO _newFile = new CE.InputOut.MyIO();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + DateTime.Now.Day.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("00") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }

        private static void CreateMailDeliveryExceptionLog(string strLocation, System.Text.StringBuilder ErrorMessage)
        {
            String[] _fileContent = new String[3];
            _fileContent[0] = "Date Time : " + DateTime.Now.ToString();
            _fileContent[1] = "Location : " + "MyMailManager - " + strLocation;
            _fileContent[2] = "Message : " + ErrorMessage;

            WriteMailDeliveryExceptionLog("MailDelivery_", _fileContent);
        }

        private static void WriteMailDeliveryExceptionLog(string strPrefixFileName, string[] strException)
        {
            try
            {
                CE.InputOut.MyIO _newFile = new CE.InputOut.MyIO();
                string _filePath = AppDomain.CurrentDomain.BaseDirectory + "Exception\\";
                if (_newFile.CheckDirectory(_filePath))
                {
                    string _curMonth = DateTime.Now.Year.ToString("0000") + DateTime.Now.Month.ToString("00");

                    if (!_newFile.CheckDirectory(_filePath + _curMonth))
                    {
                        if (_newFile.CreateDirectory(_filePath, _curMonth))
                        {
                            _filePath += _curMonth + "\\";
                        }
                    }
                    else
                    {
                        _filePath += _curMonth + "\\";
                    }

                    string _fileName = strPrefixFileName + _curMonth + DateTime.Now.Day.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("00") + ".txt";

                    _newFile.WriteNewFile(_filePath, _fileName, strException);
                    _newFile = null;
                }
            }
            catch (Exception Ex)
            {
                Ex = null;
            }
        }

        public static bool SendNewUserActivateLink(string UserName, string EmailAddress, string AuthSalt, string UniquiId, string AuthCode, CE.Global.CEUserType UserType)
        {
            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());

            string domainUrl = "";
            string ConfirmPath = "";
            string UserPath = "";
            string userType = "";

            //domainUrl = "http://" + myUri.Host;
            domainUrl = "http://" + myUri.Host + ":" + myUri.Port;
            userType = "Customer";
            ConfirmPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NewUserActivateLinkPath");
            UserPath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UserLinkPath");

            string confirmUrl = domainUrl;
            string imgUrl = domainUrl;
            confirmUrl += ConfirmPath;
            string userUrl = domainUrl;
            userUrl += UserPath;

            imgUrl += CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

            string mailBody = "";
            //mailBody += "<img src='" + imgUrl + "' />";
            mailBody += "<br>You're only one step away from creating your teledirect.com.sg account. Just click on the link below or cut and paste it into your web browser to confirm this is a working email address:";
            mailBody += "<br>" + confirmUrl + "?authkey=" + AuthSalt + "&uid=" + UniquiId + "<br>";
            mailBody += "<br>Here is your teledirect.com.sg account information: <br><br> email : " + UserName;
            mailBody += "<br>password : " + AuthCode + "<br>";
            mailBody += "<br>Once you've verified your email address, click on this link or copy and paste it into your web browser to update your profile or change your password:";
            mailBody += "<br><br>" + userUrl;
            mailBody += "<br><br><br>Thank you very much!";
            mailBody += "<br>Regards,";
            mailBody += "<br>Teledirect";

            string noreplysmtphost = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPHostName");
            string noreplysmtpport = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPPort");
            string noreplysmtpaccount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPAccount");
            string noreplysmtpdisplayname = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPDisplayName");
            string noreplysmtpreplyto = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPReplyTo");
            string noreplysmtpauthcode = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPAuthCode");
            bool noreplysmtpenablessl = Convert.ToBoolean(CE.Configuration.MyConfigurationManager.GetAppSettingValue("NoReplySMTPSslEnable"));

            bool _result = SendMailNew(noreplysmtphost,
                        Convert.ToInt32(noreplysmtpport),
                        noreplysmtpaccount,
                        noreplysmtpauthcode,
                        noreplysmtpdisplayname,
                        noreplysmtpaccount,
                        userType,
                        EmailAddress,
                        "",
                        "",
                        noreplysmtpreplyto,
                        "Almost done! Verify your Teledirect.com.sg account",
                        mailBody,
                        noreplysmtpenablessl);
            return _result;
        }
    }
}
